/*
 *  $Id: DefaultLocalizer.cs 1176 2010-11-08 11:19:45Z thenn.erannor $
 *  This file is a part of Ragima CCG.
 *  (C) 2008-2010 Ragima development group.
 *
 *  Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System;
using System.Collections.Generic;

namespace Ragima.Languages {
    /// <summary>
    /// Базовая реализация локализатора ресурсов.
    /// Сбор ресурсов в общий словарь с последующим поиском по нему.
    /// </summary>
    public class DefaultLocalizer : ILocalizer {
        private string _langCode;
        private string _prefix;
        private Dictionary<string, ILocalized> _resources;

        public DefaultLocalizer(string langCode) : this(langCode, string.Empty) {
        }
        public DefaultLocalizer(string langCode, string prefix) {
            _langCode = langCode;
            _prefix = prefix;
            _resources = new Dictionary<string, ILocalized>();
        }

        /// <summary>
        /// Добавляет ресурс во внутренний словарь.
        /// </summary>
        public void AddResource(string id, ILocalized resource) {
            _resources[id] = resource;
        }

        #region ILocalizer implementation
        public virtual string LangCode {
            get { return _langCode; }
        }

        public int ResourceCount {
            get { return _resources.Count; }
        }

        public T FindResource<T>(string id) where T : class, ILocalized {
            string key = id;
            if (!string.IsNullOrEmpty(_prefix)) {
                if (id.StartsWith(_prefix))
                    key = id.Substring(_prefix.Length);
                else
                    return null;
            }
            ILocalized resource;
            if (_resources.TryGetValue(key, out resource))
                return resource as T;
            else
                return null;
        }
        #endregion
    }
}
